package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xuecheng.api.media.model.dto.MediaDTO;
import com.xuecheng.api.media.model.dto.TeachplanMediaDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.enums.content.CourseModeEnum;
import com.xuecheng.common.enums.content.TeachPlanEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.agent.MediaApiAgent;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.convert.TeachplanMediaConvert;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.Teachplan;
import com.xuecheng.content.entity.TeachplanMedia;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanMediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanMediaServiceImpl extends ServiceImpl<TeachplanMediaMapper, TeachplanMedia> implements TeachplanMediaService {


    @Autowired
    private MediaApiAgent mediaApiAgent;

    @Autowired
    private TeachplanMediaService teachplanMediaService;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseBaseService courseBaseService;

    /*
     * 业务分析：
     *   1.判断关键数据
     *       teachplanid mediaid
     *
     *   2.判断业务数据
     *       课程计划数据
     *           判断是否存在
     *           判断课程计划是否是第三级
     *           判断是否是同一家机构的操作
     *               根据课程基础信息来查询
     *               判断课程类型是否是点播
     *       媒资数据
     *           判断是否存在
     *           判断是否是同一家机构
     *           判断媒资信息是否审核通过
     *
     *   3.保存课程计划和媒资信息关联关系
     *       判断关联数据是否存在
     *           如果不存在
     *               创建数据
     *           如果存在
     *               修改数据
     *                   mediaid 和 medianame
     *
     *
     *   4.将数据封装成dto并返回
     * */
    public TeachplanMediaDTO associateMedia(TeachplanMediaDTO dto,Long complayId) {

        //1.判断关键数据
        //    teachplanid mediaid complayId

        if (ObjectUtils.isEmpty(dto.getMediaId())||
                ObjectUtils.isEmpty(dto.getTeachplanId())||
                ObjectUtils.isEmpty(complayId)
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        //2.判断业务数据
        //    课程计划数据
        //        判断是否存在
        //        判断课程计划是否是第三级

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getId,dto.getTeachplanId());
        queryWrapper.eq(Teachplan::getGrade, TeachPlanEnum.THIRD_LEVEL);

        Teachplan teachplan = teachplanService.getOne(queryWrapper);

        if (ObjectUtils.isEmpty(teachplan)) {
            ExceptionCast.cast(ContentErrorCode.E_120402);
        }
        //        判断是否是同一家机构的操作
        //            根据课程基础信息来查询
        //            判断课程类型是否是点播
        LambdaQueryWrapper<CourseBase> baseQueryWrapper = new LambdaQueryWrapper<>();
        baseQueryWrapper.eq(CourseBase::getId,teachplan.getCourseId());
        baseQueryWrapper.eq(CourseBase::getCompanyId,complayId);
        baseQueryWrapper.eq(CourseBase::getTeachmode, CourseModeEnum.COURSE_MODE_RECORD_STATUS.getCode());
        baseQueryWrapper.eq(CourseBase::getStatus, CommonEnum.USING_FLAG.getCodeInt());

        CourseBase courseBase = courseBaseService.getOne(baseQueryWrapper);
        //判断审核状态，只能是未提交和审核已提交
        String auditStatus = courseBase.getAuditStatus();
        if (CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus)||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)
        ) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }

        //    媒资数据
        //        判断是否存在
        //        判断是否是同一家机构
        //        判断媒资信息是否审核通过
        RestResponse<MediaDTO> response = mediaApiAgent.getMediaById4s(dto.getMediaId());
        if (!(response.isSuccessful())) {
            ExceptionCast.castWithCodeAndDesc(response.getCode(),response.getMsg());
        }
        MediaDTO mediaDTO = response.getResult();
        if (!(ObjectUtils.nullSafeEquals(mediaDTO.getCompanyId(),complayId))) {
            ExceptionCast.cast(CommonErrorCode.E_100108);
        }

        String mediaDTOAuditStatus = mediaDTO.getAuditStatus();
        if (!(AuditEnum.AUDIT_PASTED_STATUS.getCode().equals(mediaDTOAuditStatus))){
            ExceptionCast.cast(ContentErrorCode.E_120415);
        }

        //3.保存课程计划和媒资信息关联关系
        //    判断关联数据是否存在
        //        如果不存在
        //            创建数据
        //        如果存在
        //            修改数据
        //                mediaid 和 medianame
        LambdaQueryWrapper<TeachplanMedia> mediaQueryWrapper = new LambdaQueryWrapper<>();
        mediaQueryWrapper.eq(TeachplanMedia::getTeachplanId,teachplan.getId());
        mediaQueryWrapper.eq(TeachplanMedia::getCourseId,teachplan.getCourseId());

        boolean result = false;
        int count = teachplanMediaService.count(mediaQueryWrapper);
        if (count < 1) {
            //        如果不存在
            //            创建数据
            TeachplanMedia teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(mediaDTO.getId());
            teachplanMedia.setTeachplanId(teachplan.getId());
            teachplanMedia.setCourseId(teachplan.getCourseId());
            teachplanMedia.setMediaFilename(mediaDTO.getFilename());

            result = teachplanMediaService.save(teachplanMedia);
        } else {
            //          如果存在
            //              修改数据
            //                  mediaid 和 medianame
            LambdaUpdateWrapper<TeachplanMedia> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(TeachplanMedia::getMediaId, mediaDTO.getId());
            updateWrapper.set(TeachplanMedia::getMediaFilename, mediaDTO.getFilename());
            updateWrapper.eq(TeachplanMedia::getTeachplanId, teachplan.getId());

            result = teachplanMediaService.update(updateWrapper);
        }
        if (!result) {
            ExceptionCast.cast(ContentErrorCode.E_120411);
        }

        //4.将数据封装成dto并返回
        LambdaQueryWrapper<TeachplanMedia> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId,teachplan.getId());

        TeachplanMedia teachplanMedia = teachplanMediaService.getOne(lambdaQueryWrapper);

        TeachplanMediaDTO resultDTO = TeachplanMediaConvert.INSTANCE.entity2dto(teachplanMedia);


        return resultDTO;

    }
}
